package com.example.musicdemo.model

import android.database.Cursor
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore

data class AudioBean(var data: String?, var size: Long, var display_name: String?, var artist: String?) :
    Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        parcel.readLong(),
        parcel.readString(),
        parcel.readString()
    ) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(data)
        parcel.writeLong(size)
        parcel.writeString(display_name)
        parcel.writeString(artist)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<AudioBean> {
        override fun createFromParcel(parcel: Parcel): AudioBean {
            return AudioBean(parcel)
        }

        override fun newArray(size: Int): Array<AudioBean?> {
            return arrayOfNulls(size)
        }


        fun getAudioBean(cursor: Cursor?):AudioBean{
            //创建bean对象
            val audioBean = AudioBean("",0,"","")

            cursor?.let { it ->
                it.getString(it.getColumnIndex(MediaStore.Audio.Media.DATA))
                    .also { audioBean.data = it }
                audioBean.size = it.getLong(it.getColumnIndex(MediaStore.Audio.Media.SIZE))

                val displayName = it.getString(it.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
                audioBean.display_name = displayName?.substring(0, displayName.lastIndexOf("."))
                val also1 = it.getString(it.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                    .also { audioBean.artist = it }
                also1
            }
            return audioBean
        }

        /**
         * 根据特定位置cursor获取整个播放列表
         */
        fun getAudioBeans(cursor: Cursor?):ArrayList<AudioBean>{
            val list = ArrayList<AudioBean>()
            cursor?.let {
                it.moveToPosition(-1)
                while (it.moveToNext()){
                    val audioBean = getAudioBean(it)
                    list.add(audioBean)
                }
            }
            return list
        }
    }



}